package com.atguigu.Threads;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 方式三：实现Callable接口，JDL 5.0新增
 * 与Runable接口相比较，Callable更为强大
 *  1.可以有返回值
 *  2.可以抛出异常
 *  3.支持泛型操作
 *  4.需要借助FutureTask类
 * @author xiaoqi
 * @data 2021/04/08 10:05
 */
class NumThread implements Callable {//支持泛型
    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            sum += i;
            System.out.println(i);
        }
        return sum;
    }

}

public class ThreadCallableDemo {
    public static void main(String[] args) {
        NumThread numThread = new NumThread();
        FutureTask task = new FutureTask<>(numThread);

        new Thread(task).start();
        try {
            //返回参数Callable对象实现类的返回值
            Object sum = task.get();
            System.out.println("总和sum为：" + sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
